package com.pengpai.pangucms.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.pengpai.pangucms.entity.Qrcode;
import com.pengpai.pangucms.service.IQrcodeService;
import com.pengpai.pangucms.utils.R;
import com.pengpai.pangucms.utils.UserUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author rxg
 * @since 2023-08-31
 */
@Controller
@RequestMapping("/qrcode")
public class QrcodeController {
    @Resource
    private IQrcodeService qrcodeService;

    @Value("${pengpai.base-url}")
    private String base_url;


    @GetMapping("/index")
    @PreAuthorize("hasAuthority('qrcode:manage:read')")
    public String index(){
        return "admin/qrcode/qrcode_index";
    }

    @GetMapping("/add")
    @PreAuthorize("hasAuthority('qrcode:manage:create')")
    public String add(){
        return "admin/qrcode/qrcode_add";
    }

    @GetMapping("edit")
    @PreAuthorize("hasAuthority('qrcode:manage:update')")
    public String edit(Model model, String qrId){
        Qrcode qrcode = qrcodeService.getById(qrId);
        model.addAttribute("qrcode",qrcode);
        return "admin/qrcode/qrcode_edit";
    }

    @GetMapping("info")
    @PreAuthorize("hasAuthority('qrcode:manage:read')")
    public String detailInfo(Model model, String qrId){
        Qrcode qrcode = qrcodeService.getById(qrId);
        model.addAttribute("qrcode",qrcode);
        return "admin/qrcode/qrcode_info";
    }


    @GetMapping("view")
    @PreAuthorize("hasAuthority('qrcode:manage:read')")
    public String view(Model model, String qrId, HttpServletResponse response){
        Qrcode qrcode = qrcodeService.getById(qrId);
        QrConfig config = new QrConfig(qrcode.getSize(), qrcode.getSize());
        config.setErrorCorrection(ErrorCorrectionLevel.H);
        String img64 = QrCodeUtil.generateAsBase64(base_url+"qrcodeScanRecord/jumpTo/" + qrcode.getUuid(),config,"png");
        model.addAttribute("img",img64);
        model.addAttribute("qrcode",qrcode);
        return "admin/qrcode/qrcode_view";
    }

    @GetMapping("/list")
    @ResponseBody
    @PreAuthorize("hasAuthority('qrcode:manage:read')")
    public Map<String,Object> list(String key, int page, int limit){

        Page<Qrcode> qrcodePage = new Page<>(page,limit);

        QueryWrapper<Qrcode> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(key), "qrcode_name", key).orderByAsc("order_id");

        List<Qrcode> webConfigs = qrcodeService.page(qrcodePage,queryWrapper).getRecords();

        Map<String, Object> map = new HashMap<>();

        map.put("code",0);
        map.put("msg","");
        map.put("count",qrcodePage.getTotal());
        map.put("data",webConfigs);
        map.put("key",key);

        return map;
    }

    @PostMapping("/create")
    @ResponseBody
    @PreAuthorize("hasAuthority('qrcode:manage:create')")
    public R create(Qrcode qrcode){

        qrcode.setUuid(UUID.randomUUID().toString());
        qrcode.setCreateUser(UserUtils.CurrentUserName());
        qrcode.setCreateTime(LocalDateTime.now());
        qrcode.setUpdateUser(UserUtils.CurrentUserName());
        qrcode.setUpdateTime(LocalDateTime.now());
        qrcodeService.save(qrcode);
        return R.success();
    }

    @PostMapping("/del")
    @ResponseBody
    @PreAuthorize("hasAuthority('qrcode:manage:delete')")
    public R del(String ids){

        List<Long> list = null;
        if(StrUtil.isNotBlank(ids)){
            list = Stream.of(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        }
        qrcodeService.removeBatchByIds(list);
        return R.success();
    }
    @PostMapping("/update")
    @ResponseBody
    @PreAuthorize("hasAuthority('qrcode:manage:update')")
    public R update(Qrcode qrcode){
        qrcode.setCreateTime(LocalDateTime.now());
        qrcodeService.updateById(qrcode);
        return R.success();
    }

    @GetMapping("/download")
    @ResponseBody
    public R downloadQrcode(Qrcode qrcode){
        qrcode = qrcodeService.getById(qrcode.getQrId());
        QrConfig config = new QrConfig(300, 300);
        String img64 = QrCodeUtil.generateAsBase64(qrcode.getJumpTo(),config,"png");

        QrCodeUtil.generate("https://hutool.cn/", 300, 300, FileUtil.file("d:/qrcode.png"));
        return R.success(img64);
    }


}
